import { TranslationService } from './services/translationService';
import { AIService } from './services/aiService';
import { LogService } from './services/logService';

console.log('开始加载 Background Script');

try {
    const translationService = new TranslationService();
    const aiService = new AIService();
    const logger = new LogService('background');
    
    logger.debug('Background 服务初始化成功');
    
    // 添加消息监听器
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        logger.debug('收到消息:', request);
        
        (async () => {
            try {
                let response;
                
                switch (request.action) {
                    case "translate":
                        logger.debug('处理翻译请求:', request.text);
                        response = await translationService.translate(request.text);
                        logger.debug('翻译完成:', response);
                        sendResponse({ translation: response });
                        break;

                    case "summarize":
                        logger.debug(`处理${request.action}请求:`, request.text);
                        response = await aiService.processRequest(request.action, request.text);
                        logger.debug(`${request.action}完成:`, response);
                        sendResponse({ summary: response });
                        break;

                    case "explain":
                        logger.debug(`处理${request.action}请求:`, request.text);
                        response = await aiService.processRequest(request.action, request.text);
                        logger.debug(`${request.action}完成:`, response);
                        sendResponse({ explanation: response });
                        break;

                    default:
                        logger.warn('未知的请求类型:', request.action);
                        sendResponse({ error: '未知的请求类型' });
                }
            } catch (error) {
                logger.error(`${request.action}请求失败:`, error);
                sendResponse({ error: error.message });
            }
        })();
        
        return true; // 保持消息通道开放
    });

    // 添加安装监听器
    chrome.runtime.onInstalled.addListener(() => {
        logger.debug('扩展已安装/更新');
    });
} catch (error) {
    console.error('Background 初始化失败:', error);
} 